package com.banshuibao.bsb_android.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.MyApplication;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.download.DownloadListActivity;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AuthorizedResultModel;
import com.banshuibao.bsb_android.model.DownloadAudioModel;
import com.banshuibao.bsb_android.model.ExpertAnswerDetailModel;
import com.banshuibao.bsb_android.model.ExpertResultModel;
import com.banshuibao.bsb_android.model.RequestAuthorizedModel;
import com.banshuibao.bsb_android.util.CCMediaConfig;
import com.banshuibao.bsb_android.util.DataSet;
import com.banshuibao.bsb_android.util.DialogUtils;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.MediaUtil;
import com.banshuibao.bsb_android.util.ParamsUtil;
import com.banshuibao.bsb_android.util.QuickDoubleClickable;
import com.banshuibao.bsb_android.util.TimeUtil;
import com.banshuibao.bsb_android.util.XToast;
import com.bokecc.sdk.mobile.download.Downloader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.cunoraz.gifview.library.GifView;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangpan on 2018/1/3.
 */

public class AnswerListenRecordAdapter extends RecyclerView.Adapter<AnswerListenRecordAdapter.ViewHolder> implements MediaPlayerUtil.MediaPlayerPlayingListener {

    private Activity context;
    private List<ExpertAnswerDetailModel.DataBean.VoicesBean> list;
    private MediaPlayerUtil mediaPlayerUtil;
    private MediaPlayer media;
    private String time;
    private PopupWindow popupWindow;
    private String questionUuid;
    private ExpertResultModel.DataBean dataBean;
    private String voiceName, voiceContent;
    private Dialog buyDialog;
    private String downUuid;

    private Handler handler = new Handler() {
        TextView textView;
        ViewHolder holder;
        private boolean stop = false;

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (!stop) {
                        sendEmptyMessageDelayed(0, 1000);
                        textView.setText(ParamsUtil.millsecondsToStr(media.getDuration() - media.getCurrentPosition()));
                        holder.show_iv.setVisibility(View.GONE);
                        holder.gifView.setVisibility(View.VISIBLE);
                    }
                    break;
                case 1:
                    holder = (ViewHolder) msg.obj;
                    textView = holder.text_tv;
                    stop = false;
                    holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
                    break;
                case 2:
                    stop = true;
                    holder.show_iv.setVisibility(View.VISIBLE);
                    holder.gifView.setVisibility(View.GONE);
                    holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
                    textView.setText(time);
                    media.seekTo(0);
                    media.pause();
                    media.stop();
                    media.reset();
                    media = null;
                    break;
                case 3:
                    if (media != null) {
                        if (media.isPlaying()) {
                            stop = true;
                            media.pause();
                            holder.show_iv.setVisibility(View.VISIBLE);
                            holder.gifView.setVisibility(View.GONE);
                        } else {
                            stop = false;
                            sendEmptyMessageDelayed(0, 1000);
                            media.start();
                        }
                    }
                    break;
            }
        }
    };

    public AnswerListenRecordAdapter(Activity context) {
        this.context = context;
        list = new ArrayList<>();
        mediaPlayerUtil = new MediaPlayerUtil(context);
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(this);
    }

    public void setData(List<ExpertAnswerDetailModel.DataBean.VoicesBean> voicesBean, ExpertResultModel.DataBean dataBean) {
        if (this.list != null) {
            this.list.clear();
            this.list.addAll(voicesBean);
            this.dataBean = dataBean;
            this.questionUuid = dataBean.getUuid();
            notifyDataSetChanged();
        }
    }

    @Override
    public AnswerListenRecordAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.recorder_list_layout, null);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final AnswerListenRecordAdapter.ViewHolder holder, final int position) {
        final ExpertAnswerDetailModel.DataBean.VoicesBean expertVoicesBean = list.get(position);
        if (expertVoicesBean != null) {
            final String uuid = expertVoicesBean.getUuid();
            final long voiceTime = expertVoicesBean.getVoiceTime();
            final String during = TimeUtil.formatDuring(voiceTime);

            holder.text_tv.setText(during);
            if (TextUtils.equals(expertVoicesBean.getUuid(), playUuid)) {
                holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listen_foucu));
            } else {
                holder.relativeLayout.setBackground(context.getResources().getDrawable(R.drawable.listenback));
            }
            holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //审请权限
                    getAuthorized(questionUuid, uuid, during, holder, "voice");
                }
            });
            holder.show_tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //审请权限
                    getAuthorized(questionUuid, uuid, during, holder, "text");
                }
            });

            if (!TextUtils.isEmpty(MyApplication.applicationInstance.getLoginInfo().getUserId()) && DataSet.hasDownloadAudioInfo(expertVoicesBean.getUuid())) {
                int status = DataSet.getDownloadAudioInfo(expertVoicesBean.getUuid()).getStatus();
                if (status == DownloadAudioModel.FINISH) {
                    holder.download_status.setImageResource(R.drawable.icon_answer_complete);
                    holder.download_status.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            IntentManager.goDownloadListActivity(context);
                        }
                    });
                } else {
                    holder.download_status.setImageResource(R.drawable.icon_answer_downling);
                    holder.download_status.setOnClickListener(null);
                }
            } else {
                holder.download_status.setImageResource(R.drawable.icon_download_start);
                holder.download_status.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (QuickDoubleClickable.isDoubleClick()) {
                            return;
                        }
                        if (!TextUtils.isEmpty(downUuid)) {
                            return;
                        }
                        downUuid = expertVoicesBean.getUuid();
                        getDownAuthorized(questionUuid, uuid, expertVoicesBean.getCreateDate(), during);
                    }
                });
            }
        }
    }

    private void download(final String uuid, final String url, final String content, final long createTime, final String voiceTime) {
        if (DataSet.hasDownloadAudioInfo(uuid)) {
            downUuid = "";
            if (DataSet.getDownloadAudioInfo(uuid).getStatus() != Downloader.FINISH) {
                XToast.showToast(context, "文件下载中,请到我的下载中查看");
            }
            XToast.showToast(context, "文件已存在");
            return;
        }
        final String path = MediaUtil.getAudioFile(CCMediaConfig.DOWNLOAD_DIR, uuid).getPath();
        if (TextUtils.isEmpty(path)) {
            downUuid = "";
            return;
        }
        Glide.with(context).load(Constants.Url.SHOW_IMAGE + dataBean.getHeadImg()).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
            @Override
            public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
                try {
                    String img = Base64.encodeToString(bytes, Base64.DEFAULT);
                    downloadStart(uuid, url, content, createTime, voiceTime, img, path);
                } catch (Exception e) {
                    downloadStart(uuid, url, content, createTime, voiceTime, "", path);
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                super.onLoadFailed(e, errorDrawable);
                downloadStart(uuid, url, content, createTime, voiceTime, "", path);
                XToast.showToast(context, "头像下载失败");
            }
        });
        XToast.showToast(context, "正在加载下载数据");
    }

    private void downloadStart(final String uuid, final String url, final String content, final long createTime, final String voiceTime, final String img, final String path) {
        DownloadAudioModel downloadAudioModel = new DownloadAudioModel();
        downloadAudioModel.setUuid(uuid);
        downloadAudioModel.setStatus(DownloadAudioModel.DOWNLOAD);
        downloadAudioModel.setContent(content);
        downloadAudioModel.setQuestion(dataBean.getQuestion());
        downloadAudioModel.setName(dataBean.getName());
        downloadAudioModel.setDuty(dataBean.getDuty());
        downloadAudioModel.setGroupId(dataBean.getUuid());
        downloadAudioModel.setCreateTime(createTime);
        downloadAudioModel.setUrl(url);
        downloadAudioModel.setVoiceTime(voiceTime);
        downloadAudioModel.setImg(img);
        DataSet.addDownloadAudiInfo(downloadAudioModel);
        downloadAudioModel.setIndexTask(FileDownloader.getImpl().create(url).
                addHeader("Accept-Encoding", "identity").
                setPath(path).
                setTag(uuid).
                setListener(listener).
                setMinIntervalUpdateSpeed(400).
                start());
        XToast.showToast(context, "文件已加入下载队列");
        downUuid = "";
    }

    /**
     * 调用援权接口获取下载信息
     */
    public void getDownAuthorized(String questionUuid, final String voiceUuid, final long createTime, final String voiceTime) {
        RequestAuthorizedModel requestAuthorizedModel = new RequestAuthorizedModel();
        requestAuthorizedModel.setUuid(questionUuid);
        requestAuthorizedModel.setVoiceId(voiceUuid);
        HttpUtil.doPost(Constants.Url.AUDIO_AUTHORIZED, requestAuthorizedModel, new HttpResponse(context, AuthorizedResultModel.class) {
            @Override
            public void onResult(Object obj) {
                AuthorizedResultModel resultModel = (AuthorizedResultModel) obj;
                AuthorizedResultModel.DataBean data = resultModel.getData();
                if (data != null) {
                    String type = data.getType();
                    if ("0".equals(type)) {
                        String url = data.getVoiceName();
                        String content = data.getVoiceText();
                        download(voiceUuid, Constants.Url.AUDIO_PLAY + url, content, createTime, voiceTime);
                    } else if ("1".equals(type)) {
                        showBuy(dataBean.getQuPrice());
                        downUuid = "";
                    }
                }
            }

            @Override
            public void onError(String code, String msg) {
                super.onError(code, msg);
                downUuid = "";
            }

            @Override
            public void onFailure(String msg) {
                super.onFailure(msg);
                downUuid = "";
            }
        });
    }

    private FileDownloadListener listener = new FileDownloadListener() {

        private long contentLength = 0;

        @Override
        protected void pending(final BaseDownloadTask task, int soFarBytes, int totalBytes) {
            notifyDataSetChanged();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        URL url = new URL(task.getUrl());
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        contentLength = connection.getContentLength();
                        connection.disconnect();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }

        @Override
        protected void started(BaseDownloadTask task) {
            super.started(task);
        }

        @Override
        protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
            updateProgress(task, soFarBytes, totalBytes, contentLength);
        }

        @Override
        protected void completed(BaseDownloadTask task) {
            String uuid = (String) task.getTag();
            int totalBytes = task.getSmallFileTotalBytes();
            String progressText = ParamsUtil.byteToKB(totalBytes) + "KB/" + ParamsUtil.byteToKB(totalBytes) + "KB";
            DownloadAudioModel downloadAudioModel = DataSet.getDownloadAudioInfo(uuid);
            if (downloadAudioModel == null)
                return;
            downloadAudioModel.setStatus(DownloadAudioModel.FINISH);
            downloadAudioModel.setProgressText(progressText);
            DataSet.updateDownloadAaudioInfo(downloadAudioModel);
            notifyDataSetChanged();
            DataSet.saveData();
            context.sendBroadcast(new Intent(CCMediaConfig.ACTION_AUDIO_DOWNLOADED));
        }

        @Override
        protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {

        }

        @Override
        protected void error(BaseDownloadTask task, Throwable e) {
            XToast.showToast(MyApplication.applicationInstance, "音频下载失败");
        }

        @Override
        protected void warn(BaseDownloadTask task) {
        }
    };

    private void updateProgress(BaseDownloadTask task, int soFarBytes, int totalBytes, long contentLength) {
        if (totalBytes <= 0)
            totalBytes = task.getSmallFileTotalBytes();
        if (totalBytes <= 0)
            totalBytes = (int) contentLength;
        if (totalBytes <= 0)
            return;
        String uuid = (String) task.getTag();
        DownloadAudioModel downloadAudioModel = DataSet.getDownloadAudioInfo(uuid);
        if (downloadAudioModel == null)
            return;
        double progress = (double) soFarBytes / (double) totalBytes * 100;
        String progressText = ParamsUtil.byteToKB(soFarBytes) + "KB/" + ParamsUtil.byteToKB(totalBytes) + "KB";
        downloadAudioModel.setProgress(progress);
        downloadAudioModel.setProgressText(progressText);
        DataSet.updateDownloadAaudioInfo(downloadAudioModel);
        context.sendBroadcast(new Intent(CCMediaConfig.ACTION_AUDIO_DOWNLOADING));
    }

    @Override
    public int getItemCount() {
        return list != null ? list.size() : 0;
    }

    @Override
    public void OnError(MediaPlayer mediaPlayer) {

    }

    @Override
    public void OnPrepared(MediaPlayer mediaPlayer) {
        //开始播放
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            handler.sendEmptyMessageDelayed(0, 1000);
        }
    }

    @Override
    public void OnCompletion(MediaPlayer mediaPlayer) {
        handler.sendEmptyMessage(2);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        LinearLayout relativeLayout;
        TextView text_tv;
        ImageView show_iv, download_status;
        TextView show_tv;
        GifView gifView;

        public ViewHolder(View itemView) {
            super(itemView);
            relativeLayout = itemView.findViewById(R.id.play);
            text_tv = itemView.findViewById(R.id.text_tv);
            show_iv = itemView.findViewById(R.id.voice_iv);
            gifView = itemView.findViewById(R.id.voice_gif);
            show_tv = itemView.findViewById(R.id.show_tv);
            show_tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
            show_tv.getPaint().setAntiAlias(true);//抗锯齿
            download_status = itemView.findViewById(R.id.download_status);
            gifView.setGifResource(R.raw.play);
        }
    }

    /**
     * 播放语音
     */
    private void playAudio(String name) {
        media = mediaPlayerUtil.getNetMedia(Constants.Url.AUDIO_PLAY + name);
    }

    public void clear() {
        if (list != null) {
            list.clear();
            list = null;
        }
        media = null;
        if (mediaPlayerUtil != null) {
            mediaPlayerUtil.clearMediaPlayer();
        }
        if (handler != null) {
            handler.sendEmptyMessage(2);
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    /**
     * 查看文字
     */
    public void showText(String content) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
        // builder.setTitle("提示"); //设置标题
        builder.setMessage(content); //设置内容
//        builder.setPositiveButton("发布", new DialogInterface.OnClickListener() { //设置确定按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
        builder.setNegativeButton("已阅", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    private String playUuid;

    /**
     * 调用援权接口是否可听可看
     */
    public void getAuthorized(String questionUuid, final String voiceUuid, final String during, final ViewHolder viewHolder, final String tag) {
        if (QuickDoubleClickable.isDoubleClick()) {
            return;
        }
        RequestAuthorizedModel requestAuthorizedModel = new RequestAuthorizedModel();
        requestAuthorizedModel.setUuid(questionUuid);
        requestAuthorizedModel.setVoiceId(voiceUuid);
        HttpUtil.doPost(Constants.Url.AUDIO_AUTHORIZED, requestAuthorizedModel, new HttpResponse(context, AuthorizedResultModel.class) {
            @Override
            public void onResult(Object obj) {
                AuthorizedResultModel resultModel = (AuthorizedResultModel) obj;
                AuthorizedResultModel.DataBean data = resultModel.getData();
                if (data != null) {
                    String type = data.getType();
                    if ("0".equals(type)) {
                        voiceName = data.getVoiceName();
                        voiceContent = data.getVoiceText();
                        if ("voice".equals(tag)) {
                            if (media != null) {
                                if (voiceUuid.equals(playUuid)) {
                                    handler.sendEmptyMessage(3);
                                } else {
                                    handler.sendEmptyMessage(2);
                                }
                            } else {
                                playUuid = voiceUuid;
                                time = String.valueOf(during);
                                Message msg = Message.obtain();
                                msg.what = 1;
                                msg.obj = viewHolder;
                                handler.sendMessage(msg);
                                playAudio(voiceName);
                            }
                        } else if ("text".equals(tag)) {
                            showText(voiceContent);
                        }

                    } else if ("1".equals(type)) {
                        voiceName = "";
                        voiceContent = "";
                        showBuy(dataBean.getQuPrice());
                    }
                }
            }
        });
    }

    /**
     * 是否购买
     */
    public void showBuy(double price) {
        buyDialog = DialogUtils.payDialog(context, "您可以支付" + price + "元购买单次或支付365元购买会员卡收听所有语音!", dataBean.getUuid(), String.valueOf(price), dataBean.getQuestion(), 5);
        if (!buyDialog.isShowing())
            buyDialog.show();
//        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(false);  //先得到构造器
//        builder.setTitle("提示"); //设置标题
//        builder.setMessage("收听/查看此问题需要支付" + price + "元"); //设置内容
//        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() { //设置确定按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//                IntentManager.goPayResultActivity(context, dataBean.getQuestion(), String.valueOf(dataBean.getQuPrice()), dataBean.getUuid(), 5);
//            }
//        });
//        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
//            @Override
//            public void onClick(DialogInterface dialog, int which) {
//                dialog.dismiss();
//            }
//        });
//        //参数都设置完成了，创建并显示出来
//        builder.create().show();
    }
}

